package com.daocao.support.config.security;


import cn.hutool.core.util.ObjectUtil;
import com.daocao.common.entity.UmsMenu;
import com.daocao.common.entity.UmsRole;
import com.daocao.common.entity.UmsSysUser;
import com.daocao.common.entity.vo.LoginUserVo;
import com.daocao.common.mapper.UmsMenuMapper;
import com.daocao.common.mapper.UmsSysUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SysUserDetailsService implements UserDetailsService {

    private final UmsSysUserMapper sysUserMapper;
    private final UmsMenuMapper umsMenuMapper;

    public SysUserDetailsService(UmsSysUserMapper sysUserMapper, UmsMenuMapper umsMenuMapper) {
        this.sysUserMapper = sysUserMapper;
        this.umsMenuMapper = umsMenuMapper;
    }

    /**
     * 根据 account 查询用户
     * @param account (account: username, mobile, email)
     * @return loginUserVo
     */
    @Override
    public UserDetails loadUserByUsername(String account) throws UsernameNotFoundException {
        int accountType = 0;
        UmsSysUser sysUser = sysUserMapper.selectUserByUsername(account, accountType);

        if (ObjectUtil.isNull(sysUser)) {
            List<UmsRole> roleList = sysUser.getRoleList();
            List<Long> roleIds = roleList.stream().map(UmsRole::getRoleId).collect(Collectors.toList());
            List<UmsMenu> menuList = umsMenuMapper.selectByRoleIds(roleIds);
            List<String> perms = menuList.stream().map(UmsMenu::getPerms).collect(Collectors.toList());
            sysUser.setPerms(perms);
        }
        LoginUserVo loginUserVo = new LoginUserVo();
        loginUserVo.setSysUser(sysUser);
        loginUserVo.setId(sysUser.getId());
        return loginUserVo;
    }
}
